<?php

namespace App\Kuafu\Shop\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ShopAttributeMappingModel extends BaseModel
{
    use HasFactory, KfSoftDeletes, KfUid;

    protected $connection = 'mysql';
    protected $table      = 'shop_attribute_mapping';
    protected $fillable   = [
        'shopId',
        'attributeId',
        'value',
        'createdAt',
        'updatedAt',
        'createdByUid',
        'updatedByUid',
        'isDeleted',
    ];


    const SEARCH_ANY = 'any';// 满足任一条件
    const SEARCH_ALL = 'all';// 满足所有条件

    public function shopAttributeMappingRel(): hasOne
    {
        return $this->hasOne(ShopAttributeModel::class, 'id', 'attributeId')->select([
            'id',
            'categoryId',
            'name',
            'remark'
        ]);
    }

    public static function updateData(int $id, array $data): int
    {
        return self::query()->where('id', $id)->update($data);
    }

    public static function getData(int $shopId, int $attributeId, string $value = '')
    {
        return self::query()
                   ->when($shopId, function ($query) use ($shopId) {
                       $query->where('shopId', $shopId);
                   })
                   ->when($attributeId, function ($query) use ($attributeId) {
                       $query->where('attributeId', $attributeId);
                   })
                   ->when($value != '', function ($query) use ($value) {
                       $query->where('value', $value);
                   })
                   ->first();
    }
}
